package webapp.mvc.controllers;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import webapp.mvc.components.HttpManager;
import webapp.mvc.controllers.forms.ChangeUserRoleForm;
import webapp.mvc.controllers.forms.SimpleResponse;
import webapp.mvc.models.RoleEntity;
import webapp.mvc.models.UserEntity;
import webapp.mvc.services.IUserService;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
@RequestMapping("/role")
public class RoleController {
    @Autowired
    private IUserService userService;
    @Autowired
    private HttpManager httpManager;

    @RequestMapping("/all")
    public
    @ResponseBody
    String getAllRoles() {
        List<RoleEntity> roleEntities = userService.getAllRoles();
        return SimpleResponse.ok(roleEntities).toJSON();
    }

    @RequestMapping("/user_roles/{userId}")
    public
    @ResponseBody
    String getRolesOfUser(HttpServletRequest request, @PathVariable String userId) {
        UserEntity userEntity = userService.findById(userId);
        if (userEntity == null) {
            return SimpleResponse.fail("找不到用户" + userId).toJSON();
        }
        List<RoleEntity> roleEntities = userService.getRolesOfUser(userEntity.getId());
        return SimpleResponse.ok(roleEntities).toJSON();
    }

    @RequestMapping(value = "/add_user_role", method = RequestMethod.POST)
    public
    @ResponseBody
    String addUserRole(HttpServletRequest request, ChangeUserRoleForm changeUserRoleForm) {
        userService.addRoleToUser(changeUserRoleForm.getUserId(), changeUserRoleForm.getRoleId());
        return SimpleResponse.ok(userService.getRolesOfUser(changeUserRoleForm.getUserId())).toJSON();
    }

    @RequestMapping(value = "/remove_user_role", method = RequestMethod.POST)
    public
    @ResponseBody
    String removeUserRole(HttpServletRequest request, ChangeUserRoleForm changeUserRoleForm) {
        userService.removeRoleFromUser(changeUserRoleForm.getUserId(), changeUserRoleForm.getRoleId());
        return SimpleResponse.ok(userService.getRolesOfUser(changeUserRoleForm.getUserId())).toJSON();
    }
}
